package com.windystory.wslibrary.net.netstatus;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.windystory.wslibrary.util.event.Event;

import org.greenrobot.eventbus.EventBus;

import static com.windystory.wslibrary.base.app.EventBusCode.EVENT_NETWORK_MOBILE;
import static com.windystory.wslibrary.base.app.EventBusCode.EVENT_NETWORK_UNKNOWN;
import static com.windystory.wslibrary.base.app.EventBusCode.EVENT_NETWORK_WIFI;

/**
 * 监听网络变化
 */
public class NetWorkChange extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
            ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(
                    Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
            if (networkInfo != null && networkInfo.isAvailable()) {
                int type2 = networkInfo.getType();
                switch (type2) {
                    case 0://移动 网络    2G 3G 4G 都是一样的 实测 mix2s 联通卡
                        EventBus.getDefault().post(new Event(EVENT_NETWORK_MOBILE));
                        break;
                    case 1: //wifi网络
                        EventBus.getDefault().post(new Event(EVENT_NETWORK_WIFI));
                        break;
                }
            } else {// 无网络
                EventBus.getDefault().post(new Event(EVENT_NETWORK_UNKNOWN));
            }
        }
    }
}
